# coding=utf-8

"""注册登录流程，并添加用户、密码验证功能，密码错误三次则退出"""

import pickle

def open_file():
	try:
		with open("user", "rb") as obj:
			return pickle.load(obj)
	except IOError:
		return False
	except Exception:
		return False


def register():
	print("开始注册账号...")
	username = input("输入用户名： ")
	user = open_file() if open_file() else {}
	if username in user:
		print("用户已存在！\n")
		return False
	password = input("输入用户密码： ")
	user[username] = password
	with open("user", "wb") as u:
		pickle.dump(user, u)
	print("注册成功！\n")


def loging():
	username = input("username: ")
	temp = open_file()
	if not temp:
		print("用户不存在\n")
		return False
	elif username not in temp:
		print("用户不存在\n")
		return False
		
	count = 0
	while count < 3:
		passwd = input("password: ")
		if passwd != temp.get(username):
			print("密码错误！")
			count += 1
			continue
		print("密码正确，登录成功\n")
		break
	else:
		print("错误三次，退出\n")


def main():
	while True:
		print("根据数字进行相关操作：")
		choise = input("1:登录 2:注册 3:退出 : ")
		if choise == "1":
			loging()
		elif choise == "2":
			register()
		else:
			print("\n退出")
			break


main()
